<template>
  <div class="tree_box">
    <tree-item
      :data="departmentData"
      @changeId="change"
      @changeIsOpenAndSelect="changeIsOpenAndSelect"
    ></tree-item>
  </div>
</template>

<script>
import treeItem from "./tree-item";
export default {
  components: {
    treeItem
  },
  props: {
    initDepartment: {
      type: Object
    }
  },
  data() {
    return {
      departmentData: [],
      count: 0,
      depId: ""
    };
  },
  computed: {
    user() {
      return this.$store.state.user;
    },
    userServiceArea() {
      if (this.$store.state.user) {
        return this.$store.state.user.serviceAreaTree;
      } else {
        return null;
      }
    }
  },
  watch: {
    userServiceArea: {
      handler: function() {
        if (this.userServiceArea) {
          this.departmentData = this.recursionFn([
            JSON.parse(JSON.stringify(this.userServiceArea))
          ]);
          if (this.initDepartment.id) {
            this.getCheckedNodes(this.initDepartment.id);
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  mounted() {
    // this.getDepartmentList();
  },
  methods: {
    recursionFn(arr) {
      arr.map((item, index) => {
        this.count++;
        item.isOpen = false;
        if (this.count == 1) {
          // 第一层默认展开
          item.isOpen = true;
        }
        if (!this.initDepartment.id && this.count == 1 && index == 0) {
          item.selected = false; //考虑到根节点性能问题，默认选中第二层第一个节点
        } else if (!this.initDepartment.id && this.count == 2) {
          item.selected = true;
          this.$emit("initCurDepartment", item.id, item.departmentName);
        } else if (
          this.initDepartment.id &&
          this.initDepartment.id == item.id
        ) {
          item.selected = true;
        } else {
          item.selected = false;
        }
        if (item.children && item.children) {
          this.recursionFn(item.children);
        }
      });
      return arr;
    },
    recursionChangeIsOpenAndSelect(arr, type, id) {
      for (let item of arr) {
        if (type == "selected") {
          item.selected = false;
        }
        if (item.id == id) {
          if (type == "isOpen") {
            item.isOpen = !item.isOpen;
          }

          if (type == "selected") {
            item.selected = true;
            this.$emit("showTreeFn", false);
          }
        }
        if (item.children && item.children.length !== 0) {
          this.recursionChangeIsOpenAndSelect(item.children, type, id);
        }
      }
      return arr;
    },
    change(id, departmentName) {
      // let resName = ''
      let parentNodes = this.findAllParent({ id }, this.departmentData);
      if (parentNodes) {
        parentNodes.pop();
        let res = parentNodes.map(e => e.departmentName).reverse();
        if (res.length) {
          departmentName = `${res.join(" / ")} / ${departmentName}`;
        }
      }
      this.$emit("changeId", id, departmentName);
      this.setCloseNodes(this.departmentData[0].children);
      this.getCheckedNodes(id);
      return { id, departmentName };
    },
    changeIsOpenAndSelect(type, id) {
      this.departmentData = this.recursionChangeIsOpenAndSelect(
        this.departmentData,
        type,
        id
      );
    },
    getDepartmentList() {
      //   this.$http(this.$API.getMyOrganization,{},true, false, true, true).then((res) => {
      //       this.departmentData = this.recursionFn([res])
      //       this.getCheckedNodes(this.initDepartment.id)
      //   })
    },
    setCloseNodes(tree) {
      for (const data of tree) {
        data.isOpen = false;
        if (data.children && data.children.length) {
          this.setCloseNodes(data.children);
        }
      }
    },
    getCheckedNodes(id) {
      if (!this.initDepartment.id) {
        return;
      }
      let departmentName = "";
      let deep = [];
      let parentNodes = this.findAllParent({ id }, this.departmentData, deep);
      let node = this.treeFind(
        this.departmentData[0].children,
        e => e.id === id
      );
      // console.log(parentNodes);
      if (!node) {
        departmentName = this.departmentData[0].departmentName;
      } else {
        departmentName = node.departmentName;
      }
      if (parentNodes) {
        parentNodes.pop();
        let res = parentNodes.map(e => e.departmentName).reverse();
        if (res.length) {
          departmentName = `${res.join(" / ")} / ${departmentName}`;
        }
      }
      // console.log(deep);
      this.$emit("initCurDepartment", id, departmentName);
      if (deep.length > 1) {
        this.setCheckedNodes(deep, this.departmentData[0].children);
      }
      return node;
    },
    setCheckedNodes(deep, tree, index = 0) {
      if (index > deep.length - 1) {
        return;
      }
      let i = deep[index];
      tree[i].isOpen = true;
      if (tree.children && tree.children.length) {
        this.setCheckedNodes(deep, tree, ++index);
      }
    },
    findAllParent(node, tree, deep = [], parentNodes = [], index = 0) {
      if (!node || !node.id) {
        return;
      }
      if (!node.parentId) {
        node = this.treeFind(tree, e => e.id === node.id);
        if (!node) {
          return;
        }
      }
      this.findParent(node, parentNodes, tree, deep);
      let parentNode = parentNodes[index];
      this.findAllParent(parentNode, tree, deep, parentNodes, ++index);
      return parentNodes;
    },
    findParent(node, parentNodes, tree, deep) {
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        if (item.id === node.parentId) {
          deep.push(i);
          parentNodes.push(item);
          return;
        }
        if (item.children && item.children.length > 0) {
          this.findParent(node, parentNodes, item.children, deep);
        }
      }
    },
    findNode(node, parentNodes, tree, deep) {
      for (let i = 0; i < tree.length; i++) {
        let item = tree[i];
        if (item.id === node.parentId) {
          deep.push(i);
          parentNodes.push(item);
          return;
        }
        if (item.children && item.children.length > 0) {
          this.findParent(node, parentNodes, item.children, deep);
        }
      }
    },
    treeFind(tree, func) {
      for (const data of tree) {
        if (func(data)) return data;
        if (data.children && data.children.length) {
          const res = this.treeFind(data.children, func);
          if (res) return res;
        }
      }
      return null;
    }
  }
};
</script>

<style lang="less"></style>
